<?php
namespace Intendant\Controller;
use Think\Controller;
use Think\Image;
use Think\Storage\Driver\File;
class ContentController extends AuthController {
	public function category(){
		if(S('category')){
			$category = S('category');
		}else{
			$category = M('category')->select();
			S('category',$category,C('AUTH_MENU_TIME'));
		}
		$this->category = category($category);
		$this->display();
	}
	// 添加栏目
	public function addCate()
	{
		$parentid = I('parentid');
		$parentid = $parentid != '' ? $parentid : 0;
		if(S('category')){
			$category = S('category');
		}else{
			$category = M('category')->select();
			S('category',$category,C('AUTH_MENU_TIME'));
		}
		$this->category = categoryTwo($category);
		$this->parentid = $parentid;

		if(IS_POST && I("addCate")){
			$rules = array(
				array('name','require',-2), //栏目名称不能为空
				array('name','',-4,0,'unique',1), //栏目名称唯一性
			);
			$cate = M("category");
			if($cate->validate($rules)->create()){
				if($id = $cate->add())
				{
					$this->ajaxReturn(-20);
				}
			}
			else
			{
				$this->ajaxReturn($cate->getError());
			}

		}
		$this->display();
	}
	// 修改栏目
	public function editCate()
	{
		$id = I('id');
		$catelist = M('category')->where(array('id'=>$id))->find();
		if(S('category')){
			$category = S('category');
		}else{
			$category = M('category')->select();
			S('category',$category,C('AUTH_MENU_TIME'));
		}

		$this->category = categoryTwo($category);
		// p($this->menu);
		$this->catelist = $catelist;
		// p($this->catelist);

		if(IS_POST && I("editCate")){
			$rules = array(
				array('name','require',-2), //栏目名称不能为空
				array('name','',-4,0,'unique',1), //栏目名称唯一性
			);
			$cate = M("category");
			if($cate->validate($rules)->create()){
				if($id = $cate->save())
				{
					$this->ajaxReturn(-20);
				}
			}
			else
			{
				$this->ajaxReturn($cate->getError());
			}

		}
		$this->display();
	}
	// 删除栏目
	public function delCate()
	{
		if(IS_POST && I('id')){
			$id = I('id');
			$db = M('category');
			$cateid = $db->field(array('id','pid'))->select();
			$delid = get_all_child($cateid,$id);

			$delid[] = $id;
			$where = array('id' => array('IN',$delid));
			$status = $db->where($where)->delete();
			$msg = returnMsg("栏目删除成功","栏目删除失败",$status);
			$this->ajaxReturn($msg);
			exit;
		}
	}
	// 栏目排序
	public function sortCate(){
		$error_id = "";
		$status = true;
		$sortRule = I("sort");
		foreach($sortRule as $k => $v){
			$data = array(
				"id"=>$k,
				"sort"=>$v
			);
			$status = M("category")->save($data);
			if ($status === false){
				$error_id = $k;
				break;//当排序失败时，捕获错误ID，结束程序
			}
		}
		$msg = returnMsg("栏目排序成功","<br />发生错误的排序ID：$error_id",$status);
		$this->ajaxReturn($msg);
	}
	public function index(){
		$this->display();
	}
	public function publicCate(){
		$where = ['isshow'=>1];
		$lanmu = M('category')
		    ->where($where)
		    ->field('id,name,pid,sort,icon as cc')
		    ->select();
		foreach($lanmu as $k3 => $v3)
        {
            $lanmu[$k3]['iconSkin'] = 'tree-icon '.$v3['cc'].' ';
            if($v3['pid'] != 0)
            {
            	$lanmu[$k3]['url'] = U('Content/main').'/catid/'.$v3['id'] .'/isshow/1';
            }
            $lanmu[$k3]['target'] = 'right';
        }
		$this->assign('json', json_encode($lanmu));
		$this->display();
	}
	public function main(){
		$catid = I('catid');
		$this->isshow = I('isshow');
		$catname = M('category')->where(['id'=>$catid])->field('name')->find();
		$this->catid = $catid;
		$this->catname = $catname['name'];
		$this->artIsyesCount = M('article')->where(['catid'=>$catid,'isshow'=>1])->count();
		$this->artIsnoCount = M('article')->where(['catid'=>$catid,'isshow'=>0])->count();
		$searchtype = I('searchtype');
		$keyword = I('keyword');
		if (!empty($searchtype)) {
            $where[$searchtype] = array('like', '%' . $keyword . '%');
        }
        //添加开始时间
        $start_time = I('get.start_time');
        if (!empty($start_time)) {
            $start_time = strtotime($start_time);
            $where['createtime'] = array("EGT", $start_time);
            $this->assign('start_time', $start_time);
        }
        //添加结束时间
        $end_time = I('get.end_time');
        if (!empty($end_time)) {
            $end_time = strtotime($end_time);
            $where['createtime'] = array("ELT", $end_time);
            $this->assign('end_time', $end_time);
        }
        // if ($status != '') {
        //     $where['status'] = $status;
        // }
        if($catid){
        	$where['catid'] = $catid;
	        $where['isshow'] = I('isshow');
			$count = M('article')->where($where)->count();
			$Page  = new \Think\Page($count,20);// 实例化分页类 传入总记录数和每页显示的记录数(25)
			// foreach($where as $key=>$val) {
			// 	$Page->parameter   .=   "$key=".urlencode($val).'&';
			// }
			$Page->setConfig('theme','%HEADER% %FIRST% %UP_PAGE% %LINK_PAGE% %DOWN_PAGE% %END%');
			$Page->setConfig('prev','上一页');
	        $Page->setConfig('next','下一页');
	        $Page->setConfig('first','第一页');
	        $Page->setConfig('last','最后一页');
	        $article = M('article')->where($where)->order('createtime desc')->limit($Page->firstRow.','.$Page->listRows)->select();
	        $show = $Page->show();// 分页显示输出
	        $this->assign("articlelist", $article);
	        $this->assign("page", $show);
        }

		$this->display();
	}
	public function sortArticle(){
		$error_id = "";
		$status = true;
		$sortRule = I("sort");
		foreach($sortRule as $k => $v){
			$data = array(
				"id"=>$k,
				"sort"=>$v
			);
			$status = M("article")->save($data);
			if ($status === false){
				$error_id = $k;
				break;//当排序失败时，捕获错误ID，结束程序
			}
		}
		$msg = returnMsg("文章排序成功","<br />发生错误的排序ID：$error_id",$status);
		$this->ajaxReturn($msg);
	}
	// 审核文章或者待审
	public function isArticle()
	{
		if(IS_POST && I('ids')){
			$id = I('ids');
			$db = M('article');
			$data['isshow'] = I('isshow');
			$where = array('id' => array('IN',$id));
			$status = $db->where($where)->save($data);
			$msg = returnMsg("文章审核成功","文章审核失败",$status);
			$this->ajaxReturn($msg);
			exit;
		}
	}
	// 批量删除文章
	public function delArticle()
	{
		if(IS_POST && I('ids')){
			$id = I('ids');
			$db = M('article');
			$where = array('id' => array('IN',$id));
			$status = $db->where($where)->delete();
			$msg = returnMsg("文章删除成功","文章删除失败",$status);
			$this->ajaxReturn($msg);
			exit;
		}
	}
	public function addArticle(){
		$catid = I('catid');
		$catname = M('category')->where(['id'=>$catid])->field('name')->find();
		$this->catid = $catid;
		$this->catname = $catname['name'];
		if(IS_POST && I("addArticle") && I('catid')){
			$rules = array(
				array('title','require',-2), //标题不能为空
				array('title','',-4,0,'unique',1), //标题唯一性
			);
			$art = M("article");
			if($art->validate($rules)->create()){
				$art->createtime = time();
				$art->username = $_SESSION['admin_user'];
				if($id = $art->add())
				{
					$this->ajaxReturn(-20);
				}
			}
			else
			{
				$this->ajaxReturn($art->getError());
			}

		}
		$this->display();
	}
	public function editArticle(){
		$catid = I('catid');
		$catname = M('category')->where(['id'=>$catid])->field('name')->find();
		$this->catid = $catid;
		$this->id = I('id');
		$article = M('article')->where(['id'=>$this->id])->find();
		$this->article = $article;
		$this->catname = $catname['name'];
		if(IS_POST && I("editArticle") && I('catid') && I('id')){
			$rules = array(
				array('title','require',-2), //标题不能为空
				array('title','',-4,0,'unique',1), //标题唯一性
			);
			$art = M("article");
			if($art->validate($rules)->create()){
				$art->createtime = time();
				$art->username = $_SESSION['admin_user'];
				if($id = $art->save())
				{
					$this->ajaxReturn(-20);
				}
			}
			else
			{
				$this->ajaxReturn($art->getError());
			}

		}
		if(!empty($article['image']))
		{
			$gmulu = __ROOT__;
			$str  = '';
			$str .= '<div class="file-item thumbnail nyxxshowimg" id="WU_FILE_'.$article['id'].'">';
			$str .=		'<input type="hidden" value="'.$article['image'].'" name="img">';
			$str .= 	'<img width="230" height="230" title="'.$article['title'].'" style="z-index:100;" src="'.$gmulu.$article['image'].'">';
			$str .= 	'<div class="info">bki-20130826161014-41271360.jpg</div>';
			$str .= 	'<div class="file-panel" style="height: 30px;">';
			$str .=			'<span class="cancel" href="javascript:void(0)" onclick=deleteImg("'.$article['id'].'","'.$article['image'].'");return false;>删除</span>';
			$str .= 		'<span class="rotateRight">向右旋转</span>';
			$str .= 		'<span class="rotateLeft">向左旋转</span>';
			$str .= 	'</div>';
			$str .=		'<div class="img-success"></div>';
			$str .= '</div>';
			$this->default_img = $str;
		}
		$this->display();
	}
	public function reArticle(){
		$this->display();
	}
	//文章封面图片上传
	public function articleImg()
	{
		if(IS_POST)
		{
			$upload = new \Think\Upload();// 实例化上传类
		    $upload->maxSize   =     314572 ;// 设置附件上传大小
		    $upload->exts      =     array('jpg', 'gif', 'png', 'jpeg');// 设置附件上传类型
		    $upload->rootPath  =     './Uploads/'; // 设置附件上传根目录
		    $upload->savePath  =     'article/images/'; // 设置附件上传（子）目录
		    $upload->saveName  =     array('uniqid','');
		    $upload->autoSub   =     true;
		    $upload->subName   =   	 array('date','Y-m-d');
		    // 上传文件
		    $info   =   $upload->upload();
		    if(!$info) {// 上传错误提示错误信息
		        $this->error($upload->getError());
		    }else{// 上传成功

		        // $this->success('上传成功！');
		        $image = new Image();
			    foreach($info as $file){
			     	//添加商品图片表
			     	// $sort++; //排序自增
			     	// $map['gid'] = $gid;
			     	// $map['goods_img'] = "/uploads/".$file['savepath'].$file['savename'];
			     	// $map['sort'] = $sort;
			     	// $goodsimg->add($map);
			     	$data['img'] = $file['savepath'].$file['savename'];
			        // 生成缩略图
			        $image->open('./Uploads/'.$file['savepath'].$file['savename']);
			        $image->thumb(350, 300,Image::IMAGE_THUMB_CENTER)->save('./Uploads/'.$file['savepath'].$file['savename']);
			        // $image->open('./uploads/'.$file['savepath'].$file['savename'])->water('./uploads/'.'logo.png',\Think\Image::IMAGE_WATER_SOUTHEAST)->save('./uploads/'.$file['savepath'].$file['savename']);
			        // echo "/uploads/".$file['savepath'].$file['savename'];
			        $this->ajaxReturn(array('info'=>"/Uploads/".$file['savepath'].$file['savename']));
			    }
		    }
		}
	}
	//删除文章封面图片
	public function delArticleImg()
	{
		//删除图片
		$img_path = '.'.I('name') ;
		$file = new File();
		// echo $img_path;
		if($file->unlink($img_path))
		{
			// 同时删除数据库信息
			$ctimg = M('article');
			$data = array(
				'image' => '',
			);
			$ctimg->where("image='".I('name')."'")->save($data);
			// $this->success('图片删除成功');
			$msg = array(
				'status' => true,
				'info' => '图片删除成功',
			);
		}
		else
		{
			$msg = array(
				'status' => false,
				'info' => '图片删除失败',
			);
		}
		$this->ajaxReturn($msg);
	}
}